<?php


namespace app\home\controller;


use think\Db;

class Guanzhu extends Base
{
    public function index(){
        $user = $this->GetUsersLatestData();
        if(!$user){
            $this->error('请先登录');
        }
        $aid = $this->request->post('aid');
        $uid = 1;//$user['id'];
        if(!$aid){
            $this->error('参数错误');
        }
        $archive = Db::name('archives')->where(['aid'=>$aid])->count();
        if(!$archive){
            $this->error('信息不存在');
        }
        $data = [
            'aid'=>$aid,
            'uid'=>$uid
        ];
        //看关注还是取消
        $count = Db::name('guanzhu')->where($data)->count();
        if($count){
            //取消
            $success = Db::name('guanzhu')->where($data)->delete();
            if(!$success){
                $this->error('操作失败');
            }else{
                $this->success('关注已取消');
            }
        }else{
            $insert_id =Db::name('guanzhu')->insert($data);
            if(!$insert_id){
                $this->error('操作失败');
            }else{
                $this->success('关注成功');
            }
        }

    }
    /**
     * 获取登录的会员最新数据
     */
    private function GetUsersLatestData($users_id = null) {
        $users_id = empty($users_id) ? session('users_id') : $users_id;
        if(!empty($users_id)) {
            $data =  Db::name('users')->field('b.*,a.*,a.id as users_id')
                ->alias('a')
                ->join('__USERS_LEVEL__ b', "a.level_id = b.id", 'LEFT')
                ->where([
                    'a.id'  => $users_id,
                ])
                ->find();
            empty($data['nickname']) && $data['nickname'] = $data['username'];
//            $data['username'] = $data['nickname'];
            empty($data['litpic']) && $data['litpic'] = ROOT_DIR . '/public/static/common/images/dfboy.png';

            return $data;
        }else{
            // session中不存在会员ID则返回空
            return false;
        }
    }
}